//
//  ToSInterFace.m
//  ToS
//
//  Created by 宁校航 on 15/8/7.
//  Copyright (c) 2015年 宁校航. All rights reserved.
//

#import "ToSInterFace.h"

@implementation ToSInterFace

#pragma mark网络状态检查
+ (void)netWorkStatus
{
    /**
     AFNetworkReachabilityStatusUnknown          = -1,  // 未知
     AFNetworkReachabilityStatusNotReachable     = 0,   // 无连接
     AFNetworkReachabilityStatusReachableViaWWAN = 1,   // 3G
     AFNetworkReachabilityStatusReachableViaWiFi = 2,   // WiFi
     */
    // 如果要检测网络状态的变化,必须用检测管理器的单例的startMonitoring
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
    // 检测网络连接的单例,网络变化时的回调方法
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        [TOSConfig sharedInstance].currentNetStatus = status;
    }];
}


#pragma mark  - Post Json
+ (void)postJSONWithMethod:(NSString *)method parameters:(id)parameters success:(void (^)(id responseObject))success fail:(void (^)())fail

{
    NSString *webURL = method;
//    NSString *webURL_convert = [webURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *webUrl_convert = [webURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 设置请求格式
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    // 设置返回格式
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
//    超时时间
    manager.requestSerializer.timeoutInterval = 120;
    
    NSLog(@"postAddress:%@ postParameters:%@",webURL,parameters);
    
    [manager POST:webUrl_convert parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"%@",uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if(success){
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if(fail)
        {
            fail();
        }
    }];
}

/**
 * 下载文件
 */
+ (void)downloadFileURL:(NSString *)aUrl savePath:(NSString *)aSavePath success:(void (^)(id responseObject))success fail:(void (^)())fail;
{
    //本地文件地址
    NSString *fileName = aSavePath;

    aUrl = [aUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    //下载附件
    NSURL *url = [[NSURL alloc] initWithString:aUrl];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        //返回文件路径
        return [NSURL fileURLWithPath:fileName];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        if (error) {
            [fileManager removeItemAtPath:fileName error:&error];
            fail();
        }
        else
        {
            [fileManager moveItemAtPath:fileName toPath:aSavePath error:&error];
            NSLog(@"DownSuccess");
            success(@"success");
            
        }
    }];
    
    
    [task resume];
}

+ (BOOL)downloadFileWithURL:(NSString *)aUrl AndSavePath:(NSString *)aSavePath
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSString *tempPath = [aSavePath stringByAppendingString:@".tmp"];
    
    if(![fileManager fileExistsAtPath:[aSavePath stringByDeletingLastPathComponent]])
    {
        [fileManager createDirectoryAtPath:[aSavePath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    aUrl = [aUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    //下载附件
    NSURL *url = [[NSURL alloc] initWithString:aUrl];
    
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    
    NSURLSession *manager = [NSURLSession sharedSession];
    NSURLSessionDownloadTask *task = [manager downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        if (error) {
            [fileManager removeItemAtPath:tempPath error:&error];
        }
        else
        {
            [fileManager moveItemAtURL:location toURL:[NSURL fileURLWithPath:aSavePath] error:&error];
        }
        
        dispatch_semaphore_signal(semaphore);
    }];
    
    [task resume];
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
    if (task.error) {
        return false;
    }
    
    return true;
}

+ (BOOL)downloadFileWithOperation:(DownloadOperation *)operation AndSavePath:(NSString *)aSavePath AndFileInfo:(LocalDownloadModel *)downloadModel
{
    long long currentNum = downloadModel.currentNum;
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if ([fileManager fileExistsAtPath:aSavePath]) {
//        downloadModel.currentNum += [NSData dataWithContentsOfFile:aSavePath].length;
        return true;
    }
    else
    {
        if ([[aSavePath pathExtension] compare:@"zip" options:NSCaseInsensitiveSearch] == NSOrderedSame)
        {
            NSString *folderPath = [aSavePath stringByDeletingPathExtension];
            if ([fileManager fileExistsAtPath:folderPath]) {
//                downloadModel.currentNum += [NSData dataWithContentsOfFile:aSavePath].length;
                return true;
            }
        }
    }
    
    NSString *tempPath = [aSavePath stringByAppendingString:@".tmp"];
    
    if(![fileManager fileExistsAtPath:[aSavePath stringByDeletingLastPathComponent]])
    {
        [fileManager createDirectoryAtPath:[aSavePath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    NSURLRequest *request = [NSURLRequest requestWithURL:operation.requestUrl];
    
    //检查文件是否已经下载了一部分
    unsigned long long downloadedBytes = 0;
    if ([[NSFileManager defaultManager] fileExistsAtPath:tempPath]) {
        //获取已下载的文件长度
        downloadedBytes = [self fileSizeForPath:tempPath];
        if (downloadedBytes > 0) {
            NSMutableURLRequest *mutableURLRequest = [request mutableCopy];
            NSString *requestRange = [NSString stringWithFormat:@"bytes=%llu-", downloadedBytes];
            [mutableURLRequest setValue:requestRange forHTTPHeaderField:@"Range"];
            request = mutableURLRequest;
        }
    }
    
    //不使用缓存，避免断点续传出现问题
    [[NSURLCache sharedURLCache] removeCachedResponseForRequest:request];
    
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    if (downloadModel.resumeData) {
        operation.afOperation = [manager downloadTaskWithResumeData:downloadModel.resumeData progress:^(NSProgress * _Nonnull downloadProgress) {
            NSLog(@"%f",1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
            downloadModel.currentNum = currentNum + downloadProgress.completedUnitCount + downloadedBytes;
            float allLength = downloadModel.allNum;
            downloadModel.processNum = downloadModel.currentNum/allLength;
            
            if (operation.isCancelled == true) {
                [operation.afOperation cancel];
            }
        } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
            return [NSURL fileURLWithPath:tempPath];
        } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
            dispatch_semaphore_signal(semaphore);
        }];
    }
    else
    {
        operation.afOperation = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
            
            NSLog(@"%f",1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
            downloadModel.currentNum = currentNum + downloadProgress.completedUnitCount + downloadedBytes;
            float allLength = downloadModel.allNum;
            downloadModel.processNum = downloadModel.currentNum/allLength;
            
            if (operation.isCancelled == true) {
                [operation.afOperation cancel];
            }
            
        } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
            
            //返回文件路径
            return [NSURL fileURLWithPath:tempPath];
            
        } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
            dispatch_semaphore_signal(semaphore);
        }];
    }
    
    
    [operation.afOperation resume];
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
    NSError *error = nil;
    if (operation.afOperation.error || operation.isCancelled == true) {
        return false;
    }
    
    downloadModel.resumeData = nil;
    [fileManager moveItemAtPath:tempPath toPath:aSavePath error:&error];
    
    return true;
}

//获取已下载的文件大小
+ (unsigned long long)fileSizeForPath:(NSString *)path {
    signed long long fileSize = 0;
    NSFileManager *fileManager = [NSFileManager new]; // default is not thread safe
    if ([fileManager fileExistsAtPath:path]) {
        NSError *error = nil;
        NSDictionary *fileDict = [fileManager attributesOfItemAtPath:path error:&error];
        if (!error && fileDict) {
            fileSize = [fileDict fileSize];
        }
    }
    return fileSize;
}

@end
